package com.example.finance_manager.dao;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.example.finance_manager.db.SQLiteHelper;
import com.example.finance_manager.models.Payout;
import com.example.finance_manager.models.User;

import java.util.ArrayList;
import java.util.List;

public class UserDao {
    private final SQLiteHelper sqLiteHelper;
    private SQLiteDatabase db;

    public UserDao(Context context) {
        sqLiteHelper = new SQLiteHelper(context);
    }

    public long add(User user) {
        db = sqLiteHelper.getWritableDatabase();
        ContentValues cv = new ContentValues();
        cv.put("username", user.getUsername());
        cv.put("password", user.getPassword());
        return db.insert("user", null, cv);
    }

    public List<User> findByUsername(String username) {
        System.out.println(username);
        List<User> userList = new ArrayList<>();
        db = sqLiteHelper.getReadableDatabase();
        Cursor cursor = db.query("user", new String[]{"id", "password", "username"}, "username = ?", new String[]{username}, null, null, null);

        while (cursor.moveToNext()) {
            User user = new User();
            user.setId(cursor.getInt(0));
            user.setUsername(cursor.getString(1));
            user.setPassword(cursor.getString(2));
            userList.add(user);
        }
        return userList;
    }

    public void update(User user) {
        Integer id = (Integer) user.getId();
        db = sqLiteHelper.getWritableDatabase();
        ContentValues cv = getContentView(user);
        db.update("user", cv, "id = ?", new String[]{id.toString()});
    }

    public List<User> findAll() {
        List<User> list = new ArrayList<User>();
        db = sqLiteHelper.getReadableDatabase();
        Cursor cursor = db.query("user", new String[]{"id", "username", "password"}, null, null, null, null, null);
        while (cursor.moveToNext()) {
            User user = new User();
            System.out.println(cursor.getInt(0));
            user.setId(cursor.getInt(0));
            user.setUsername(cursor.getString(1));
            user.setPassword(cursor.getString(2));
            list.add(user);
        }
        return list;
    }


    private ContentValues getContentView(User user) {
        ContentValues cv = new ContentValues();
        cv.put("username", user.getUsername());
        cv.put("password", user.getPassword());
        return cv;
    }
}
